import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { ApiResponse } from '../interfaces/api-response.interface';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();
    const exceptionResponse = exception.getResponse();

    let message = 'Internal server error';
    const code = status;

    // 处理异常消息
    if (typeof exceptionResponse === 'object' && exceptionResponse !== null) {
      if ('message' in exceptionResponse) {
        const msg = exceptionResponse.message;
        if (Array.isArray(msg) && msg.length > 0) {
          message = String(msg[0]);
        } else if (typeof msg === 'string') {
          message = msg;
        }
      }
    } else if (typeof exceptionResponse === 'string') {
      message = exceptionResponse;
    }

    // 生成请求ID
    const requestId =
      (request.headers['x-request-id'] as string) || this.generateRequestId();

    const errorResponse: ApiResponse<null> = {
      code,
      message,
      data: null,
      timestamp: Date.now(),
      requestId,
    };

    response.status(status).json(errorResponse);
  }

  private generateRequestId(): string {
    return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }
}
